<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">






  
  
  <link rel="stylesheet" media="all" href="/lib/Han/dist/han.min.css?v=3.3">




<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/logo.jpg?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/logo.jpg?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="ASP.NET Core,MVC,路由," />










<meta name="keywords" content="ASP.NET Core,MVC,路由">
<meta property="og:type" content="article">
<meta property="og:title" content="ASP.NET Core MVC中的路由（1）路由配置基础">
<meta property="og:url" content="http://durow.vip/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/index.html">
<meta property="og:site_name" content="Durowの隅">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1030/201610300000.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1024/201610240001.png">
<meta property="og:image" content="http://durow.gitee.io/source/images/2016/1024/201610240201.png">
<meta property="og:updated_time" content="2018-03-23T05:52:35.752Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ASP.NET Core MVC中的路由（1）路由配置基础">
<meta name="twitter:image" content="http://durow.gitee.io/source/images/2016/1030/201610300000.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"right","display":"always","offset":12,"b2t":true,"scrollpercent":true,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://durow.vip/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/"/>





  <title>ASP.NET Core MVC中的路由（1）路由配置基础 | Durowの隅</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?b5605a7aa8d230851edcda67de588833";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-right page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Durowの隅</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">forever love, forever dream</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-sitemap">
          <a href="/sitemap.xml" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-sitemap"></i> <br />
            
            站点地图
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="st-search-show-outputs">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <form class="site-search-form">
  <input type="text" id="st-search-input" class="st-search-input st-default-search-input" />
</form>

<script type="text/javascript">
  (function(w,d,t,u,n,s,e){w['SwiftypeObject']=n;w[n]=w[n]||function(){
    (w[n].q=w[n].q||[]).push(arguments);};s=d.createElement(t);
    e=d.getElementsByTagName(t)[0];s.async=1;s.src=u;e.parentNode.insertBefore(s,e);
  })(window,document,'script','//s.swiftypecdn.com/install/v2/st.js','_st');

  _st('install', 'jv23s59-xwQTfQjP6xPi','2.0.0');
</script>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://durow.vip/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="durow">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/logo.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Durowの隅">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">ASP.NET Core MVC中的路由（1）路由配置基础</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-10-24T14:41:00+08:00">
                2016-10-24
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/NET-Core/" itemprop="url" rel="index">
                    <span itemprop="name">.NET Core</span>
                  </a>
                </span>

                
                
                  ， 
                
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/NET-Core/MVC/" itemprop="url" rel="index">
                    <span itemprop="name">MVC</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/" class="leancloud_visitors" data-flag-title="ASP.NET Core MVC中的路由（1）路由配置基础">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body han-init-context" itemprop="articleBody">

      
      

      
        <p><img src="http://durow.gitee.io/source/images/2016/1030/201610300000.png" alt="ASP.NET"></p>
<a id="more"></a>
<h2 id="0x00-路由在MVC中起到的作用"><a href="#0x00-路由在MVC中起到的作用" class="headerlink" title="0x00 路由在MVC中起到的作用"></a>0x00 路由在MVC中起到的作用</h2><p>前段时间一直忙于别的事情，终于搞定了继续学习.NetCore。这次学习的主题是MVC中的路由。路由是所有MVC框架都会实现的一个组件，核心功能就是根据接收到的Http请求中的Path（对于<a href="http://localhost/Home/Index/12?test=555" target="_blank" rel="noopener">http://localhost/Home/Index/12?test=555</a> 来说，http是协议，localhost是域，Home/Index/12是Path，test=555是参数）部分，依次和路由规则集合中的规则进行匹配，匹配成功后由对应的Controller中的对应Action进行Http请求的处理。匹配不到则返回404错误。</p>
<p><img src="http://durow.gitee.io/source/images/2016/1024/201610240001.png" alt="路由"></p>
<p>大多数MVC框架路由规则的配置都大同小异，一般都是通过模板的方式来配置路由规则。有的还支持在Controller和Action上通过Attribute（Java中叫注解）进行更细粒度的配置。</p>
<p>ASP.NET Core MVC支持通过全局的路由模板配置路由规则，也支持在Controller和Action上通过Attribute进行细粒度的路由配置。下面先说一下在Startup.cs中配置全局路由规则。</p>
<h2 id="0x01-在Startup-cs中配置路由"><a href="#0x01-在Startup-cs中配置路由" class="headerlink" title="0x01 在Startup.cs中配置路由"></a>0x01 在Startup.cs中配置路由</h2><p>所谓的路由的模板就是一串字符串，当接收到Http请求后取出其中的Path部分，和模板进行对照，如果匹配模板则路由到对应的Controller和Action进行处理。我们可以在Startup.cs文件中的Configure方法中，添加MVC功能时进行路由配置，例如：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">app.UseMvc(routes =&gt;</span><br><span class="line">&#123;</span><br><span class="line">    routes.MapRoute(</span><br><span class="line">        name: <span class="string">"default"</span>,</span><br><span class="line">        template: <span class="string">"&#123;controller&#125;/&#123;action&#125;/&#123;id&#125;"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>其中name为路由规则的名称，template为路由模板。这也引出了我们第一个概念，路由模板中的变量。</p>
<h3 id="1-路由模板中的变量"><a href="#1-路由模板中的变量" class="headerlink" title="1.路由模板中的变量"></a>1.路由模板中的变量</h3><p>在模板”{controller }/{action }/{id}”中，用花括号括起来的是路由模板中的变量。例如其中变量的作用并不是必须在Path中匹配某个固定的字符串，而是起到一个占位的作用，例如上面的模板就可以匹配由“/”隔开的共三部分的Path，例如a/b/c可以匹配成功。而各个变量的值从Path中对应部分提取出来。例如</p>
<ul>
<li>Home/Index/12可以匹配，其中controller为Home，action为Index，id为12</li>
<li>Home/Index则匹配失败，因为只有2部分</li>
<li>Home/Index/12/34同样匹配失败，因为超过了3部分。</li>
</ul>
<p>模板匹配成功后，会根据controller和action提取出的值路由：</p>
<ul>
<li>Home/Index/12会路由到HomeController的Index方法，变量id为12</li>
<li>Test/Show/ab会路由到TestController的Show方法，变量id为ab</li>
</ul>
<h3 id="2-变量值得获取"><a href="#2-变量值得获取" class="headerlink" title="2.变量值得获取"></a>2.变量值得获取</h3><p>在Index或Show方法中，我们可以有两种方法提取变量：</p>
<p>一种是在方法的参数列表中加入和变量相同名称的参数，MVC会自动从变量列表中寻找并转换为对应类型：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> IActionResult <span class="title">Index</span>(<span class="params"><span class="keyword">string</span> id, <span class="keyword">string</span> controller, <span class="keyword">string</span> action</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    ViewData[<span class="string">"Message"</span>] = <span class="string">"id is "</span> + id + <span class="string">",  controller is "</span> + controller + <span class="string">",  action is "</span> + action;</span><br><span class="line">    <span class="keyword">return</span> View();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>另一种就是从RouteData中取出：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> IActionResult <span class="title">Index</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">var</span> controller = RouteData.Values[<span class="string">"controller"</span>].ToString();</span><br><span class="line">    <span class="keyword">var</span> action = RouteData.Values[<span class="string">"action"</span>].ToString();</span><br><span class="line">    <span class="keyword">var</span> id = RouteData.Values[<span class="string">"id"</span>].ToString();</span><br><span class="line">    ViewData[<span class="string">"Message"</span>] = <span class="string">"id is "</span> + id + <span class="string">",  controller is "</span> + controller + <span class="string">",  action is "</span> + action;</span><br><span class="line">    <span class="keyword">return</span> View();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>路由模板中的变量名称是可以自己定义的，但controller和action（包括后面讲的area）都是比较特殊的变量。其中controller提取出的值作为Controller的名称，action提取出的值作为Controller中方法的名称。为了让每条路由规则都能够路由到Controller和Action，在路由模板中都应该出现controller和action变量，但我们也可以给controller和action变量指定默认值，这样在Path中省略了这部分时会用默认值代替。</p>
<h3 id="3-变量的默认值"><a href="#3-变量的默认值" class="headerlink" title="3.变量的默认值"></a>3.变量的默认值</h3><p>由两种方法可以配置变量的默认值：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">app.UseMvc(routes =&gt;</span><br><span class="line">&#123;</span><br><span class="line">    routes.MapRoute(</span><br><span class="line">        name: <span class="string">"default"</span>,</span><br><span class="line">        template: <span class="string">"&#123;controller=Home&#125;/&#123;action=Index&#125;/&#123;id=0&#125;"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
<p>或者</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">routes.MapRoute(</span><br><span class="line">    name: <span class="string">"default"</span>,</span><br><span class="line">    template: <span class="string">"&#123;controller&#125;/&#123;action&#125;/&#123;id&#125;"</span>,</span><br><span class="line">    defaults: <span class="keyword">new</span> </span><br><span class="line">    &#123;</span><br><span class="line">        controller = ”Home”,</span><br><span class="line">        action = ”Index”,</span><br><span class="line">        id = <span class="number">0</span>,</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<p>这样配置后Path中带有默认值的部分可以省略，省略的规则和C#中带默认值的参数一样，例如：</p>
<ul>
<li>空Path会被路由到HomeController，Index方法</li>
<li>Test会被路由到TestController，Index方法</li>
<li>Test/Show依然会被路由到TestController，Show方法</li>
</ul>
<p>一般我会用第一种方法配置默认值，更加直观和方便。但有时候有些需求是第一种方法难以做到的。例如我想给TestController的Show方法配置路由为TestShow，使用第一种方法可以这样配置：”TestShow/{controller=Test}/{action=Show}”，这样配置当Path为TestShow时的确可以路由到TestController的Show方法，但当Path为TestShow/Home/Index时会路由到HomeController的Index方法。</p>
<p>使用第二种方法配置：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">routes.MapRoute(</span><br><span class="line">    name: <span class="string">"test"</span>,</span><br><span class="line">    template: <span class="string">"TestShow"</span>,</span><br><span class="line">    defaults: <span class="keyword">new</span> </span><br><span class="line">    &#123;</span><br><span class="line">        controller = ”Test”,</span><br><span class="line">        action = ”Show”, </span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<p>当Path为TestShow时可以路由到TestController的Show方法，但Path为Test/Home/Index则无法匹配模板。关于细粒度的路由配置更好的方法是给Test方法使用Route特性（Attribute）进行配置，后面会说到。</p>
<h3 id="4-路由规则中的静态字符"><a href="#4-路由规则中的静态字符" class="headerlink" title="4.路由规则中的静态字符"></a>4.路由规则中的静态字符</h3><p>除了使用变量来配置路由模板，还可以使用静态字符串。静态字符串可以单独使用，也可以与变量混合使用。</p>
<p>例如模板为：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Durow/&#123;controller&#125;/&#123;action&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>Durow/Home/About会路由到HomeController，About方法</li>
<li>Durow/Test/Show会路由到TestController，Show方法</li>
</ul>
<p>也可以把静态字符和变量混合起来，例如配置模板为：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">My&#123;controller&#125;/My&#123;action&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>MyHome/MyAbout会被路由到HomeController，About方法</li>
<li>MyTest/MyShow会被路由到TestController，Show方法</li>
</ul>
<h3 id="5-使用-标记变量可选"><a href="#5-使用-标记变量可选" class="headerlink" title="5.使用?标记变量可选"></a>5.使用?标记变量可选</h3><p>除了通过给变量提供默认值使其可选外，也可以使用?把变量标记为可选。例如模板</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;controller&#125;/&#123;action&#125;/&#123;id?&#125;</span><br></pre></td></tr></table></figure>
<p>其中id为可选变量，这样配置后</p>
<p>Home/Index和Home/Index/12都会成功匹配。</p>
<h3 id="6-使用-提取Path中剩余的所有部分"><a href="#6-使用-提取Path中剩余的所有部分" class="headerlink" title="6.使用*提取Path中剩余的所有部分"></a>6.使用*提取Path中剩余的所有部分</h3><p>如果一个模板需要匹配包含任意多个部分（Segments）的Path，可以使用*符号指定变量，使用*制定过的变量会把Path中匹配完成后剩余部分全部提取出来，例如模板：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&#123;controller&#125;/&#123;action&#125;/&#123;id?&#125;/&#123;*others&#125;</span><br></pre></td></tr></table></figure>
<p>Home/Index/12/a/b/c/d，会路由到HomeController的Index方法，id为12，others为a/b/c/d</p>
<p>实际上仅从模板匹配的角度来说，上面的模板可以匹配所有的Path。唯一的问题就是匹配后对应的Controller和Action可能不存在。</p>
<h3 id="7-多条路由规则的选择"><a href="#7-多条路由规则的选择" class="headerlink" title="7.多条路由规则的选择"></a>7.多条路由规则的选择</h3><p>实际应用中很可能会配置多条路由规则，当接收到Path时很可能不止一条规则能够匹配。</p>
<p>最简单的，我们配置以下两条模板：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&#123;controller &#125;/&#123;action =About&#125;</span><br><span class="line"></span><br><span class="line">&#123;controller &#125;/&#123;action =Index &#125;</span><br></pre></td></tr></table></figure>
<p>当Path为Home时两条路由都能匹配，那要怎么选择呢？其实很简单粗暴，就是看哪条路由在前面。也就是说Path一旦成功匹配到模板后就会立即实施路由并忽略后面的模板。对于上面的配置来说Home会被路由到HomeController的About方法。所以在配置路由时一定要注意顺序。</p>
<h2 id="0x02-使用Attribute配置路由"><a href="#0x02-使用Attribute配置路由" class="headerlink" title="0x02 使用Attribute配置路由"></a>0x02 使用Attribute配置路由</h2><p>除了在Startup.cs中配置全局路由规则外，也可以针对单个Controller和其中的Action配置路由。方法就是在Controller类和Action方法上使用Route特性。例如在TestController的Show方法上使用Route特性：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">[<span class="meta">Route(<span class="meta-string">"TestShow"</span>)</span>]</span><br><span class="line"><span class="function"><span class="keyword">public</span> IActionResult <span class="title">Show</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="keyword">return</span> View();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>当Path为TestShow时，即可路由到TestController的Show方法。</p>
<p>上面我们在介绍默认值时提到过，通过全局模板配置：</p>
<figure class="highlight cs"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">routes.MapRoute(</span><br><span class="line">    name: <span class="string">"test"</span>,</span><br><span class="line">    template: <span class="string">"TestShow"</span>,</span><br><span class="line">    defaults: <span class="keyword">new</span> </span><br><span class="line">    &#123;</span><br><span class="line">        controller = ”Test”,</span><br><span class="line">        action = ”Show”, </span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>
<p>也可以达到同样的目的。不过区别在于，使用后一种方法时，如果还有<code>{controller}/{action}</code>这样的模板，除了TestShow外，当Path为Test/Show可以匹配这个模板并路由到TestController的Show方法。而通过在Show方法上配置Route特性后，只有TestShow才可以路由，即使同时存在”{controller}/{action}”这样的模板，Test/Show也无法路由。</p>
<p>第一次接触用Route特性配置路由时，我很疑惑路由组件是如何把Path路由到对应的Controller和Action的，后来下了个断点看了下RouteData对象，发现对于配置了路由的Action方法，其controller为方法所在的Controller的名称，action为方法的名称，而且在Route特性配置的路由模板中不能够使用{controller}变量和{action}变量。这样就保证了匹配模板的Path总能路由到这个Action。</p>
<p>对于在Controller类上配置的Route特性最终会分别配置到Controller中的每个Action上。例如我们在TestController上配置Route(“TestShow”)，实际上就是给每个方法配置了Route(“TestShow”)，所以当Path为TestShow时会报错，提示有两个action满足匹配。那么应当如何给Controller通过Route配置路由呢，可以使用[controller]和[action]。</p>
<h3 id="Route特性中的-controller-和-action"><a href="#Route特性中的-controller-和-action" class="headerlink" title="Route特性中的[controller]和[action]"></a>Route特性中的[controller]和[action]</h3><p>对于[controller]和[action]我也不知道该怎么叫，不能叫变量，功能上类似占位符。当我们在Controller类用Route特性配置路由时，如果使用了[controller]和[action]，这样当Route特性给Controller中每个Action配置路由时，[controller]会被替换为Controller名称，[action]会被替换为Action名称。举个例子还是给TestController配置Route特性，配置为Route(“durow/[controller]/[action]”)，这样对于其中的Index方法来说，其路由模板为”durow/Test/Index”，controller为Test，action为Index。而对于Show方法来说路由模板为”durow/Test/Show”，controller为Test，action为Show。前面说过MVC会为每个Action创建一个ActionDescriptor对象存储这个Action的路由信息。对于配置了Route特性的Action（再重复一下，给Controller类配置Route特性相当于给Controller中的每个Action配置Route特性），其ActionDescriptor中会有一个AttributeRouteInfo对象，对于未配置Route特性的Action，该对象为空。AttributeRouteInfo中包含了路由模板信息。</p>
<p><img src="http://durow.gitee.io/source/images/2016/1024/201610240201.png" alt="路由"></p>
<p>所以对于上面TestController的Route特性的配置，配置为Route(“durow/Test/[action]”)也能达到同样的效果。不过使用Route(“durow/[controller]/[action]”)语义更强更通用。</p>
<h3 id="在Route特性中使用变量"><a href="#在Route特性中使用变量" class="headerlink" title="在Route特性中使用变量"></a>在Route特性中使用变量</h3><p>在Route特性中配置模板也是可以使用变量的，同样可以使用?标记变量可选。例如可以给TestController配置<code>Route(&quot;durow/[controller]/[action]/{id?}&quot;)</code>。但需要注意的是Route特性的模板中变量不能使用默认值（包括[controller]和[action]），也不能使用*提取Path所有剩余部分。</p>
<h2 id="0x03-写在最后"><a href="#0x03-写在最后" class="headerlink" title="0x03 写在最后"></a>0x03 写在最后</h2><p>啰啰嗦嗦居然写了这么多，其实实际使用中很可能用不到多么复杂的路由，一般一条通用规则，一条Area相关的规则就可以了。不过详细了解了路由规则，当以后遇到有些奇葩的特殊需求时能够有更加开阔的思路。后面讲讨论一下路由模板中的约束和自定义约束。再后面讨论一下使用Areas。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>如果觉得有用请打赏一杯咖啡，谢谢 :P</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/WeChatPay.png" alt="durow 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/AliPay.jpg" alt="durow 支付宝"/>
        <p>支付宝</p>
      </div>
    

    
      <div id="bitcoin" style="display: inline-block">
        <img id="bitcoin_qr" src="/images/BitcoinPay.png" alt="durow 比特币"/>
        <p>比特币<br>地址:1433nFc4GmHj1gnXdhzA4T944WqSdBajuo</p>
      </div>
    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    durow
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://durow.vip/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/" title="ASP.NET Core MVC中的路由（1）路由配置基础">http://durow.vip/2016/10/24/NetCore/ASP-NET-Core-MVC中的路由（1）路由配置基础/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/ASP-NET-Core/" rel="tag"># ASP.NET Core</a>
          
            <a href="/tags/MVC/" rel="tag"># MVC</a>
          
            <a href="/tags/路由/" rel="tag"># 路由</a>
          
        </div>
      

      
      
        <div class="post-widgets">
        

        

        
          
          <div id="needsharebutton-postbottom">
            <span class="btn">
              <i class="fa fa-share-alt" aria-hidden="true"></i>
            </span>
          </div>
        
        </div>
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/10/13/CS/使用C-处理基于比特流的数据/" rel="next" title="使用C#处理基于比特流的数据">
                <i class="fa fa-chevron-left"></i> 使用C#处理基于比特流的数据
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/10/30/NetCore/ASP-NET-Core-MVC中的路由（2）在路由中使用约束/" rel="prev" title="ASP.NET Core MVC中的路由（2）在路由中使用约束">
                ASP.NET Core MVC中的路由（2）在路由中使用约束 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=2159540" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      <div id="lv-container" data-id="city" data-uid="MTAyMC8zNTAyNi8xMTU2Mg=="></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/logo.jpg"
                alt="durow" />
            
              <p class="site-author-name" itemprop="name">durow</p>
              <p class="site-description motion-element" itemprop="description">热爱生活 热爱学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">53</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">42</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="http://www.qq.com" target="_blank" title="16141860">
                      
                        <i class="fa fa-fw fa-qq"></i>16141860</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:durow@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/durow" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/durow" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>Weibo</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://space.bilibili.com/13399420/" target="_blank" title="Bilibili">
                      
                        <i class="fa fa-fw fa-tv"></i>Bilibili</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://www.twitter.com/durow1984" target="_blank" title="Twitter">
                      
                        <i class="fa fa-fw fa-twitter"></i>Twitter</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-heart"></i>
                好站推荐
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://cnblogs.com/" title="博客园" target="_blank">博客园</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#0x00-路由在MVC中起到的作用"><span class="nav-number">1.</span> <span class="nav-text">0x00 路由在MVC中起到的作用</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x01-在Startup-cs中配置路由"><span class="nav-number">2.</span> <span class="nav-text">0x01 在Startup.cs中配置路由</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-路由模板中的变量"><span class="nav-number">2.1.</span> <span class="nav-text">1.路由模板中的变量</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-变量值得获取"><span class="nav-number">2.2.</span> <span class="nav-text">2.变量值得获取</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-变量的默认值"><span class="nav-number">2.3.</span> <span class="nav-text">3.变量的默认值</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#4-路由规则中的静态字符"><span class="nav-number">2.4.</span> <span class="nav-text">4.路由规则中的静态字符</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#5-使用-标记变量可选"><span class="nav-number">2.5.</span> <span class="nav-text">5.使用?标记变量可选</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#6-使用-提取Path中剩余的所有部分"><span class="nav-number">2.6.</span> <span class="nav-text">6.使用*提取Path中剩余的所有部分</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#7-多条路由规则的选择"><span class="nav-number">2.7.</span> <span class="nav-text">7.多条路由规则的选择</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x02-使用Attribute配置路由"><span class="nav-number">3.</span> <span class="nav-text">0x02 使用Attribute配置路由</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Route特性中的-controller-和-action"><span class="nav-number">3.1.</span> <span class="nav-text">Route特性中的[controller]和[action]</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#在Route特性中使用变量"><span class="nav-number">3.2.</span> <span class="nav-text">在Route特性中使用变量</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#0x03-写在最后"><span class="nav-number">4.</span> <span class="nav-text">0x03 写在最后</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      
        <div class="back-to-top">
          <i class="fa fa-arrow-up"></i>
          
            <span id="scrollpercent"><span>0</span>%</span>
          
        </div>
      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">durow</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">Site words total count&#58;</span>
    
    <span title="Site words total count">47.2k</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>



  <div class="footer-custom">Hosted by <a target="_blank" href="https://coding.net/pages" style="font-weight:bold">Coding Pages</a></div>


        







        
      </div>
    </footer>

    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  
    <script type="text/javascript">
      (function(d, s) {
        var j, e = d.getElementsByTagName(s)[0];
        if (typeof LivereTower === 'function') { return; }
        j = d.createElement(s);
        j.src = 'https://cdn-city.livere.com/js/embed.dist.js';
        j.async = true;
        e.parentNode.insertBefore(j, e);
      })(document, 'script');
    </script>
  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("Ai37u86U95uCssl57jjMliaH-gzGzoHsz", "QeIwQbw9Ndwl2sh4uawjySJJ");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  
  
  <link rel="stylesheet" href="/lib/needsharebutton/needsharebutton.css">

  
  
  <script src="/lib/needsharebutton/needsharebutton.js"></script>

  <script>
    
      pbOptions = {};
      
          pbOptions.iconStyle = "default";
      
          pbOptions.boxForm = "horizontal";
      
          pbOptions.position = "middleRight";
      
          pbOptions.networks = "Wechat,Weibo,Douban,QQZone,Evernote,Twitter";
      
      new needShareButton('#needsharebutton-postbottom', pbOptions);
    
    
  </script>

  

  
  
    <script type="text/x-mathjax-config">
      MathJax.Hub.Config({
        tex2jax: {
          inlineMath: [ ['$','$'], ["\\(","\\)"]  ],
          processEscapes: true,
          skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
        }
      });
    </script>

    <script type="text/x-mathjax-config">
      MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for (i=0; i < all.length; i += 1) {
          all[i].SourceElement().parentNode.className += ' has-jax';
        }
      });
    </script>
    <script type="text/javascript" src="//cdn.bootcss.com/mathjax/2.7.1/latest.js?config=TeX-AMS-MML_HTMLorMML"></script>
  


  

  

</body>
</html>
